﻿//
// Created by 17616 on 2021/5/27.
//

#ifndef TIFFREADER_FINDERDATA_HPP
#define TIFFREADER_FINDERDATA_HPP
#include "OpenXLSX.hpp"
#include <filesystem>
#include <map>
#include <unordered_map>
using namespace OpenXLSX;

// 此类用于封装对excel的读写，
class FinderData {
public:
    FinderData() {
        idxMap["编号"] = 1;
        idxMap["当量"] = 2;
        idxMap["x"] = 3;
        idxMap["y"] = 4;
        idxMap["w"] = 5;
        idxMap["h"] = 6;
        idxMap["H"] = 7;
        idxMap["S"] = 8;
        idxMap["光通量积分"] = 10;
        idxMap["光通量估计"] = 11;
    }
    void open(std::string path) {
        if (!std::filesystem::exists(path)) {
            doc.create(path);
            wks = doc.workbook().worksheet("Sheet1");
            wks.cell(1, 1).value() = "编号";//编号
            wks.cell(1, 2).value() = "当量";
            wks.cell(1, 3).value() = "x";
            wks.cell(1, 4).value() = "y";
            wks.cell(1, 5).value() = "w";
            wks.cell(1, 6).value() = "h";
            wks.cell(1, 7).value() = "H";//色相
            wks.cell(1, 8).value() = "S";//色饱和不低于1半
            wks.cell(1, 9).value() = "从这列开始可以自行使用";//色饱和不低于1半

        } else {
            doc.open(path);
            wks = doc.workbook().worksheet("Sheet1");
        }
        Size = wks.rowCount() - 1;
        for (int i = 0; i < Size; ++i) {
            auto buf = operator()("编号", i).value().get<int>();
            idxRef[buf] = i;
        }
    }

    inline XLCell operator()(std::string col, int32_t row) {
        if (row < 0) {
            row += size();
        }
        return wks.cell(row + 2, idxMap[col]);
    }

    //增加一行
    void addRow() {
        for (int i = 0; i < size(); ++i) {
            max_idx = MAX(max_idx, operator()("编号", i).value().get<int>());
        }
        max_idx++;
        operator()("编号", Size).value() = max_idx;
        operator()("H", Size).value() = rand() % 360;
        operator()("S", Size).value() = 128 + rand() % 128;
        idxRef[max_idx] = Size;
        Size++;
    }
    void save() {
        doc.save();
    }
    uint32_t size() {
        return Size;
    }
    inline int idxOFref(int ref) {
        return idxRef[ref];
    }

    uint32_t max_idx{0};//最大的编号


private:
    uint32_t Size;
    std::unordered_map<std::string, int> idxMap;
    std::unordered_map<int, int> idxRef;

    XLDocument doc;
    XLWorksheet wks;
};


#endif //TIFFREADER_FINDERDATA_HPP
